package com.example.getappinfodemo

import android.annotation.SuppressLint
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat


class MainActivity : AppCompatActivity() {
    val TAG = MainActivity::class.java.name
    private val textView :TextView by lazy { findViewById(R.id.tvTest) }

    private val requestUsageStatsLauncher: ActivityResultLauncher<Intent> =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            // 用户从设置页面返回后触发
            if (Constants.hasUsageStatsPermission(this)) {
                Log.i(TAG, "用户已授权，开始获取应用信息")
                doWithUsageStats() // 授权后立即获取应用信息
            } else {
                Log.i(TAG, "用户未授权，无法获取应用信息")
                textView.text = "请授予应用使用统计权限"
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        initView()
    }

    private fun initView() {
        // 检查权限，若未授权则引导用户开启
        if (!Constants.hasUsageStatsPermission(this)) {
            Constants.requestUsageStatsPermission(this,requestUsageStatsLauncher)
        } else {
            // 已获得权限，执行需要该权限的逻辑（如获取应用使用时长）
            doWithUsageStats()
        }
        textView.setOnClickListener {
            getTopApp(this)
        }
    }

    private fun doWithUsageStats() {
        getTopApp(this)
    }

    @SuppressLint("SetTextI18n")
    private fun getTopApp(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val m = context.getSystemService(USAGE_STATS_SERVICE) as UsageStatsManager
            if (m != null) {
                val now = System.currentTimeMillis()
                //获取60秒之内的应用数据
                val stats = m.queryUsageStats(UsageStatsManager.INTERVAL_BEST, now - 60 * 1000, now)
                Log.i(TAG, "Running app number in last 60 seconds : " + stats!!.size)

                var topActivity = ""


                //取得最近运行的一个app，即当前运行的app
                if ((stats != null) && (!stats.isEmpty())) {
                    var j = 0
                    for (i in stats.indices) {
                        if (stats[i].lastTimeUsed > stats[j].lastTimeUsed) {
                            j = i
                        }
                    }
                    topActivity = stats[j].packageName
                }
                textView.text = "获取到的应用信息为$topActivity"
                Log.i(TAG, "top running app is : $topActivity")
            }
        }
    }
}